<?php

namespace app\api\controller;

use addons\third\model\Third;
use addons\third\model\ThirdCoach;
use addons\third\model\ThirdStudent;
use app\common\controller\Api;
use app\common\model\Attachment;
use app\admin\model\User;
use app\admin\model\Wxuser;
use app\common\model\Config;
use app\common\model\OrganizationCoachUser;
use app\common\model\StudentUser;
use EasyWeChat\Factory;
use EasyWeChat\Kernel\Messages\Article;
use EasyWeChat\Kernel\Messages\Image;
use EasyWeChat\Kernel\Messages\News;
use EasyWeChat\Kernel\Messages\NewsItem;
use EasyWeChat\Kernel\Messages\Text;
use EasyWeChat\Kernel\Messages\Video;
use EasyWeChat\Kernel\Messages\Voice;
use think\Db;
use think\Exception;
use think\Log;

class Wechat extends Api
{
    
    protected $noNeedLogin = ['jssdk', 'verify_api','getWechatConfig', 'sync_wxuser_to_system'];
    protected $noNeedMember = ['jssdk', 'verify_api','getWechatConfig', 'sync_wxuser_to_system'];
    protected $noNeedStoreId=[];

    public function __construct()
    {
        parent::__construct();
    }
    public function verify_api(){
        //验证
        //Log::write(file_get_contents('php://input'), Log::DEBUG);
        $options = [];
        if (isset($_GET["echostr"])) {
            $options = $this->getWechatConfig();
            $signature =$this->request->param('signature');
            $timestamp =$this->request->param('timestamp');
            $nonce =$this->request->param('nonce');
            $echostr =$this->request->param('echostr');
            $token = $options['token'];
            $array = array($token, $timestamp, $nonce); //放到一个数组里
            sort($array, SORT_STRING); // 将三个参数进行字典排序
            $str = implode($array); // 将三个参数拼接成一个字符串
            $str = sha1($str); // 进行 sha1加密
            if ($signature == $str) {
                ob_clean();
                echo $echostr;
                exit();
            } else {
                return false;
            }
        }
        $this->responseWechatMsg($options);
    }
    public function responseWechatMsg($options = []){
        if (!$options) {
            $options = $this->getWechatConfig();
        }
        $app = Factory::officialAccount($options);
        $server = $app->server;

        $userService = $app->user;
        $customeService = $app->customer_service;
        $server->push(function ($message) use ($userService, $customeService) {
            trace($message);
            /*Log::info("####返回数据");
            Log::info($message);*/
            // 注意，这里的 $message 不仅仅是用户发来的消息，也可能是事件
            // 当 $message->MsgType 为 event 时为事件
            if (!empty($message) && isset($message['MsgType'])) {
                if ($message['MsgType'] == 'event') {
                    $openid = $message['FromUserName'];
                    switch ($message['Event']) {
                        //关注
                        case 'subscribe':
                            $userInfo = [];
                            try {
                                $userInfo = $userService->get($openid);
                                $res = $this->saveUserInfo($userInfo);
                            } catch (\Exception $e) {
                                Log::write($e->getMessage(), Log::ERROR);
                            }
                            $replyContent = "";
                            if (!empty($userInfo)) {
//                                $replyContent = "亲爱的{$userInfo['nickname']} 您好，欢迎关注公众号";
                            }

                            return $replyContent;
                            break;
                        //取消关注
                        case 'unsubscribe':
                            $this->unsubscribe($openid);
                            break;
                        //已关注
                        case 'SCAN':
                            try {
                                $userInfo = $userService->get($openid);
                                $res = $this->saveUserInfo($userInfo);
                            } catch (\Exception $e) {
                                Log::write($e->getMessage(), Log::ERROR);
                            }

                            break;
//                        case 'CLICK':
//                            $eventKey = $message['EventKey'];
//                            return $this->keywordResponse($eventKey);
                        default:
                            # code...
                            break;
                    }
                }/*else if ($message['MsgType'] == 'text'){
                    return $this->keywordResponse($message['Content']);
                }else{
                    //  收到消息 统一回复
                    $text = Config::getConfigValue('received_reply_content','value');
                    if($text){
                        $res = new Text($text);
                        return $res;
                    }
                }*/
            }
        });
        $response = $server->serve();
        
        $response = $response->send();
        
        exit;
    }

    /**
     * 保存用户信息
     *
     * @param [array] $userInfo
     * @return bool
     */
    protected function saveUserInfo($userInfo){
        $isReplyMessage = 1;

        $unionid = !empty($userInfo['unionid']) ? $userInfo['unionid'] : '';

        $Third = new Third();
        $User = new User();
        $uid = 0;
        Db::startTrans();
        try {
            $where = ['openid' => $userInfo['openid'], 'platform'=>Third::PLATFORM_WECHAT];
            $thirdUserInfo = $Third->where($where)->find();
            $data = [
                'platform' => Third::PLATFORM_WECHAT,
                'openid' => $userInfo['openid'],
                'openname' => $userInfo['nickname'],
//                'subscribe_time' => $userInfo['subscribe_time'],
//                'subscribe' => $userInfo['subscribe'] == 1 ? Third::SUBSCRIBE_YES : Third::SUBSCRIBE_NO,
                'logintime'     => time(),
                'unionid'=> $unionid
            ];
            if($unionid){
                $old_third = $Third->where('unionid', $unionid)->find();
                if($old_third){
                    $data['openname'] = $old_third['openname'];
                    $uid = $old_third['user_id'];
                }
            }
            if ($thirdUserInfo) {
                if($thirdUserInfo['user_id']){
                    $uid = $thirdUserInfo['user_id'];
                }
                $data['user_id'] = $uid;
                $thirdUserInfo->isUpdate(true)->save($data);
            } else {
                $data['user_id'] = $uid;
                $Third->create($data);
            }
            Db::commit();
        } catch (\Exception $e) {
            trace('wechat_subscribe_event_error:' . $e->getMessage(),'error');
            Db::rollback();
            return 3;
        }
        if($uid>0){
            $user = $User->where(['id' => $uid])->find();
            if ($user) {
                $user->save([
                    'is_follow_public_wechat' => User::FOLLOW_YES,
                    // 'is_bind_wechat' => !empty($weminiApp['unionid']) && !empty($unionid) ? User::BIND_WECHAT_YES : User::BIND_WECHAT_NO
                ]);
            }
        }
        
        return $isReplyMessage;

    }
    /**
     * 取消关注
     *
     * @param [string] $openid
     * @return void
     */
    protected function unsubscribe($openid){
        $ThirdModel = new Third();
        $User = new User();
        $thirdInfo= $ThirdModel->where(['openid'=>$openid, 'platform'=>Third::PLATFORM_WECHAT])->order('id DESC')->find();
        if(!$thirdInfo){
            return true;
        }
//        $thirdInfo->save([
//            'subscribe'=>Third::SUBSCRIBE_NO
//        ]);
        if($thirdInfo['user_id']<=0){
            return true;
        }
        $user = $User->where(['id'=> $thirdInfo['user_id']])->find();
        if(!$user){
            return true;
        }
        $user->save([
            'is_follow_public_wechat' => User::FOLLOW_NO
        ]);
        $thirdInfo->save(['user_id' => 0]);
        return true;
    }
    /**
     * 同步微信关注用户到系统
     *
     * @return string
     */
    // 同步微信关注用户到系统
    public function sync_wxuser_to_system(){
        if(!config('app_debug')){
            echo '请开启调试模式';
            exit();
        }
        set_time_limit(0);
        $options=$this->getWechatConfig();
        $app = Factory::officialAccount($options);
        $userService = $app->user;
        $response = $userService->list(); // $nextOpenId 可选
        $list = $response->data['openid'];
        $success_count = 0;
        $fail_count = 0;
        foreach ($list as $key => $value) {
            $userInfo = $userService->get($value);
            $res = $this->saveUserInfo($userInfo);
            if($res != 3){
                $success_count++;
            }else{
                $fail_count++;
            }
        }
        echo "同步成功：{$success_count} 同步失败：{$fail_count}";
    }
    /**
     * 获取公众号配置信息
     *
     * @return array
     */
    protected function getWechatConfig(){
        $data['debug'] = false;
        $data['app_id'] = Config::getConfigValue('wechat_appid', 'value');
        $data['secret'] = Config::getConfigValue('wechat_secret', 'value');
        $data['token'] = Config::getConfigValue('token', 'value');
        $data['aes_key'] = Config::getConfigValue('aes_key', 'value');
//        $data['app_id'] = "";
//        $data['secret'] = "";
//        $data['token'] = "";
//        $data['aes_key'] = "";
        if(empty($data['app_id'])|| empty($data['secret'])|| empty($data['token'])|| empty($data['aes_key'])){
            trace('公众号配置信息未完善','error');
        }
        return $data;
    }

    /**
     * 关注词回复
     */
    /*
    protected function keywordResponse($keyword, $storeId)
    {
        $keyword = model('WechatKeyword')
        ->where(['keywords' => $keyword,'store_id' => $storeId])
        ->find();
        if($keyword){
            if($keyword['type'] != WechatKeyword::TYPE_TEXT){
                $keywordku = model('wechatKeywordKu')->where(['id' => $keyword['media_id']])->find();
            }
            switch($keyword['type']){
                case WechatKeyword::TYPE_IMG:
                    $res = new Image($keywordku['media_id']);
                    break;
                case WechatKeyword::TYPE_TEXT:
                    $res = new Text($keyword['text']);
                    break;
                case WechatKeyword::TYPE_VIDEO:
                    $res = new Video($keywordku['media_id']);
                    break;
                case WechatKeyword::TYPE_VOICE:
                    $res = new Voice($keywordku['media_id']);
                    break;
                case WechatKeyword::TYPE_ALLL:
                    $items = [
                        new NewsItem([
                            'title'       => $keywordku['content_title'],
                            'description' => $keywordku['content'],
                            'url'         => $keywordku['content_url'],
                            'image'       => $keywordku['content_image'],
                            // ...
                        ]),
                    ];
                    $res = new News($items);
                    break;
            }
            return $res;
        }else{
            //  收到消息回复
            $text = Config::getConfigValue('received_reply_content', 'value', $storeId);
            if($text){
                $res = new Text($text);
                return $res;
            }
        }

        return '';
    }
    */

    /**
     * 获取首页图片封面id
     */
    protected function getThumbMediaIdByImage($sharePoster, $app, $key = false) {
        if (!$key) {
            $key = 'register_wechat_template_media_' . $sharePoster;
        }
        $thumb_media_id = '';
        if ($sharePoster) {
            $cacheKey = md5($key);
            $thumb_media_id = cache($cacheKey);
            if (!$thumb_media_id) {
                // 处理图片
                $sharePoster = getRealImg($sharePoster);
                
                // 上传临时素材
                try {
                    $result = $app->media->upload('image', getcwd() . $sharePoster);
                    $thumb_media_id = $result['media_id'];
                    cache($cacheKey, $thumb_media_id, ['expire' => 255600]);
                } catch (\Exception $e) {
                    Log::write('code: ' . $e->getCode() . ', message: '. $e->getMessage(), Log::ERROR);
                }
            }
        }

        return $thumb_media_id;
    }

    public function jssdk()
    {
        if (!$this->request->isPost()) {
            $this->error('请求方式错误！');
        }
        try {
            $url = $this->request->post('url');
            if (!$url) {
                throw new Exception('url不能为空！');
            }
            $url = htmlspecialchars_decode($url);

            $apis = $this->request->param('apis/a', []);
            $debug = $this->request->param('debug', false);

            $config = $this->getWechatConfig();
            $app = Factory::officialAccount($config);
            
            $app->jssdk->setUrl($url);
            $config = $app->jssdk->buildConfig($apis, $debug, false, false);
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }

        $this->success('', $config);
    }

    public function upload() 
    {
        action('api/common/wx_upload');
    }

}